import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios' 

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    islogin : sessionStorage.getItem("islogin") ? 1 : 0,
    user : sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")) : null,

    cartList:[],
    count2:0,
    count3:0,
  },
  mutations: {
    updateLoginState(state,user){
      state.islogin = 1;
      state.user = user;
    },


    //以下是购物车内容函数
    // _addCartList(state,product){
    //   let isExists = false
    //   state.cartList.forEach((item)=>{
    //     if(item.pid == product.pid){
    //       item.count += product.count
    //       isExists = true
    //     }
    //   })
    //   if(!isExists){
    //     let list = product
    //     state.cartList.push(list)
    //   }
    //  },
     _addCartList(state,product){
      let isExists = false
      state.cartList.forEach((item)=>{
        if(item.pid == product.pid){
          item.count += product.count
          isExists = true
          state.count2+=product.count
        }
      })
      if(!isExists){
        state.cartList.push(product)
        state.count2+=product.count
      }
     },
    // cartlist count 添加
    _addNum(state,pid){
      state.cartList.forEach(item=>{
        if(item.pid == pid)
        item.count++
        state.count2++
        return item.count
      })
    },

    // cartlist count 减少
    _reduceNum(state,pid){
      state.cartList.forEach(item=>{
        if(item.pid == pid){
          if(item.count > 0){
            item.count--
            state.count2--
          }
        }
        return item.count
      })
    },

    // 删除购物车 数据
    _removeCartItem(state,id){
      state.cartList.forEach((item,index) => {
        if(id == item.pid){
          state.cartList.splice(index,1)
        }
      })
      return state.cartList
    },

    _removeCartAll(state){
      return state.cartList.splice(0);
    }

  },
  getters:{
    // 获取购物车列表
    _getCartList(state){
      console.log(state.cartList)
      return state.cartList
    }
  },
  
  actions: {
  },
  modules: {
  }
})
